//
//  subscribeController.m
//  Focus
//
//  Created by dlios on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "subscribeController.h"
#import "WebColor.h"
#import "weatherViewController.h"
#import "UIImageView+WebCache.h"
#import "Block_cell.h"
#import "AutoScrollView.h"
#import "UIImage+Tint.h"
#import "discoverController.h"
#import "WeiPlist.h"
#import "NetHandler.h"
#import "DXAlertView.h"
#import "discoverTitleController.h"
#import "webViewController.h"
#import "recommendController.h"
#import "ArticleViewController.h"
#import "WebImageViewController.h"
#import "ImageViewController.h"
@interface subscribeController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, retain)NSDictionary *dataDic; // 解析网络data的字典
@property (nonatomic, retain)NSArray *dataArray;// 首页模块数组
@property (nonatomic, assign)NSInteger arg;// 长压开关
@property (nonatomic, assign)NSInteger temp;// cell的位置
@property (nonatomic, retain)NSMutableArray *dataCountArray;// 总模块数组
@property (nonatomic, retain)NSMutableDictionary *kkkk;  // 解析出的详细模块字典
@property (nonatomic, retain)NSArray *listArray; // 解析出的scrollViewlist数组

@property (nonatomic, retain)NSDictionary *dic;

@end

@implementation subscribeController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
        [notiCenter addObserver:self selector:@selector(recetiveNotification:) name:@"weatherChange" object:nil];
       
        
       // 当第二次进入app的时候 会读取本地的天气信息
        NSUserDefaults *myUser = [NSUserDefaults standardUserDefaults];
        if ([myUser objectForKey:@"first"] == nil) {

            [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"first"];
            
            
            [myUser synchronize];
           
        } else {
            
            self.weather = [[Weather alloc]init];
            self.weather.title = [[NSUserDefaults standardUserDefaults] objectForKey:@"title"];
            self.weather.tmax  = [[NSUserDefaults standardUserDefaults]objectForKey:@"tmax"];
            self.weather.tmin = [[NSUserDefaults standardUserDefaults] objectForKey:@"tmin"];
            self.weather.weather_day = [[NSUserDefaults standardUserDefaults]objectForKey:@"weather_day"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"weatherChange" object:self.weather userInfo:nil];
        }
        self.kkkk = [NSMutableDictionary dictionary];
        [self checkPlist];
        
    }
    return self;
}


- (void)checkPlist
{
#pragma mark 对沙盒里plst归档
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"apiBlockSorts.plist"];
    NSDictionary *readDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    if (readDic == nil) {
        NSString *str = [[NSBundle mainBundle] pathForResource:@"apiBlockSorts" ofType:@"plist"];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:str];
        BOOL result = [dic writeToFile:filePath atomically:YES];
        if (result) {
            //            NSLog(@"apiBlockSorts.plist归档成功");
        } else {
            //            NSLog(@"apiBlockSorts.plist归档失败");
        }
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    [super dealloc];
    [_dataDic release];
    [_dataCountArray release];
    [_dataArray release];
    [_kkkk release];
    [_listArray release];
    [_pageControl release];
    [_scrollView release];
    [_blockArray release];
    [_block release];
    [_autoScrollView release];
    [_collectionView release];
    [_weather release];
    
}

- (void)recetiveNotification:(NSNotification *)notiCenter
{
#pragma mark 对天气button铺view
    Weather *city = notiCenter.object;
//    NSLog(@"*(*(*(*(   %@",city.title);
    
    if (city.title != nil) {
        self.navigationItem.rightBarButtonItem.title = city.title;
        
        UIButton *view = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(70, 20, 50, 20)];
        name.userInteractionEnabled = YES;
        [view addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        name.font = [UIFont systemFontOfSize:14];
        [view addSubview:name];
        name.text = city.title;
        NSLog(@"*(*(*(*(/*/*/*   %@",name.text);
        UILabel *temperature = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 50, 20)];
        
        temperature.font = [UIFont systemFontOfSize:14];
        [view addSubview:temperature];
        temperature.text = [NSString stringWithFormat:@"%@~%@", city.tmin, city.tmax];
        temperature.userInteractionEnabled = YES;
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(45, 0, 30, 30)];
        
        img.userInteractionEnabled = YES;
        [view addSubview:img];
#pragma mark 判断天气选择天气图片
        if ([city.weather_day isEqualToString:@"qing"]) {
            img.image = [UIImage imageNamed:@"iconfont-qing.png"];
        } else if ([city.weather_day isEqualToString:@"duoyun"]) {
            img.image = [UIImage imageNamed:@"iconfont-duoyun.png"];
        } else if ([city.weather_day isEqualToString:@"zhenyu"]) {
            img.image = [UIImage imageNamed:@"iconfont-t04.png"];
        } else if ([city.weather_day isEqualToString:@"xiaoyu"]) {
            img.image = [UIImage imageNamed:@"iconfont-4xiaoyu.png"];
        } else if ([city.weather_day isEqualToString:@"yin"]) {
            img.image = [UIImage imageNamed:@"iconfont-yintian.png"];
        } else if ([city.weather_day isEqualToString:@"xiaoyu"]) {
            img.image = [UIImage imageNamed:@"iconfont-t12.png"];
        } else if ([city.weather_day isEqualToString:@"yujiaxue"]) {
            img.image = [UIImage imageNamed:@"iconfont-iconfontyujiaxue"];
        }
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
        
        [view release];
        [name release];
        [img release];
        [temperature release];
        [self updateData];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [self updateData];
}
- (void)updateData
{
    [WeiPlist localSave: @"rootBlocks" comaletion:^(id result) {
        NSDictionary *dic = result;
        
        self.dataArray = [dic objectForKey:@"blocksData"];
        [self.collectionView reloadData];
        //        NSLog(@"nijnion%d",self.dataArray.count);
    }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    
#pragma mark 网络解析滚动视图的数据
    NSString *str = @"http://iphone.myzaker.com/zaker/follow_promote.php?_appid=AndroidPhone&_dev=18&_udid=864182029800498&_version=4.52&m=1414032616";
    self.navigationController.navigationBar.translucent = NO;
#pragma mark 修饰navigationController
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    [titleLabel setTextColor:[WebColor white]];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [titleLabel setText:@"订阅"];
    self.navigationItem.titleView = titleLabel;
    [titleLabel release];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
    if (self.weather.title == nil) {
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"获取天气" style:UIBarButtonItemStyleBordered target:self action:@selector(buttonClicked:)];
    } else {
        [self recetiveNotification:nil];
    }
    
    self.navigationItem.rightBarButtonItem.tintColor = [WebColor white];
    
#pragma mark 创建collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(104, 95);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.minimumLineSpacing = 2;
    flowLayout.sectionInset = UIEdgeInsetsMake(self.view.frame.size.height / 13 * 5, 2, 1, 2);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 65) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [WebColor white];
    [self.view addSubview:self.collectionView];
    [self.collectionView release];
    
#pragma mark 创建滚动视图
    self.autoScrollView = [[AutoScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 11 * 4)];
    self.autoScrollView.timeInterval = 5;
    self.autoScrollView.pageControlAlignment = AutoScrollViewPageControlAlignmentCenter;
    [self.collectionView addSubview:self.autoScrollView];
    [self.collectionView registerClass:[Block_cell class] forCellWithReuseIdentifier:@"reuse"];
    [self.autoScrollView setTarget:self action:@selector(scrollViewTap:)];
    
    [NetHandler networkWithURL:str comaletion:^(id result) {
        NSMutableArray *imageArray = [NSMutableArray array];
        NSMutableArray *titleArray = [NSMutableArray array];
        NSDictionary *dataDic = [result objectForKey:@"data"];
        self.listArray = [dataDic objectForKey:@"list"];
#pragma mark 解析滚动视图的4张图片
        for (NSDictionary *dic in self.listArray) {
            [imageArray addObject:[dic objectForKey:@"promotion_img"]];
            [titleArray addObject:[dic objectForKey:@"title"]];
        }
        [self.autoScrollView setTitleArray:titleArray];
        [self.autoScrollView setImageUrls:imageArray];
    }];
}
#pragma mark 点击scrollView响应的事件
- (void)scrollViewTap:(AutoScrollView *)sender
{
    //    NSLog(@"pageNo : %d", sender.pageNo);
    
    for (NSDictionary *dic in self.listArray) {
        dic = self.listArray[sender.pageNo];
        
        for (NSString *str in [dic allKeys]) {
#pragma mark 传给推荐界面
            if ([str isEqual: @"topic"]) {
                NSDictionary *dicTopcic = [dic objectForKey:@"topic"];
                NSString *strID = [dicTopcic objectForKey:@"pk"];
                ArticleViewController *art = [[ArticleViewController alloc]init];
                
                art.ID = strID;
                [self presentViewController:art animated:YES completion:^{
                    
                }];
            }
#pragma mark 传给webView
            else if ([str isEqualToString:@"web"]) {
                NSString *strURL = [[dic objectForKey:@"web"]objectForKey:@"url"];
                //                NSLog(@"%@",strURL);
                webViewController *webVC = [[webViewController alloc]init];
                webVC.url = strURL;
                webVC.integer = 1;
                webVC.i = 1;
                [self presentViewController:webVC animated:YES completion:^{
                    
                }];
#pragma mark 传给模块详细界面
            } else if ([str isEqualToString:@"block_info"]) {
                NSString *strAPI_URL = [[dic objectForKey:@"block_info"]objectForKey:@"api_url"];
                
                discoverTitleController *disTC = [[discoverTitleController alloc]init];
                
                disTC.api_url = strAPI_URL;
                
                [self presentViewController:disTC animated:YES completion:^{
                    
                }];
#pragma mark 传给webView
            } else if ([str isEqualToString:@"article"]) {
                NSDictionary *webDic = [dic objectForKey:@"article"];
                
                webViewController *webVC = [[webViewController alloc]init];
                
                NSString *str = [webDic objectForKey:@"weburl"];
                
                webVC.url = str;
                webVC.integer = 1;
                webVC.i = 1;
                [self presentViewController:webVC animated:YES completion:^{
                    
                }];
            }
        }
    }
}

#pragma mark 创建collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Block_cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
#pragma mark 判断创建模块的个数与数据数组中的相比
    if (indexPath.item < [self.dataArray count]) {
        cell.block_label.text = [self.dataArray[indexPath.item]objectForKey:@"block_title"];
        cell.block_label.font = [UIFont systemFontOfSize:11];
        [cell.block_imageView sd_setImageWithURL:[NSURL URLWithString:[self.dataArray[indexPath.item]objectForKey:@"pic"]]completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            NSDictionary *dic1 = self.dataArray[indexPath.item];
            NSString *str2 = [dic1 objectForKey:@"block_color"];
            cell.block_imageView.image = [cell.block_imageView.image imageWithTintColor:[self hexStringToColor:str2]];
//            cell.layer.cornerRadius = 20;
//            cell.backgroundColor = [WebColor gray];
            
        }];
    } else {
        [cell.block_imageView setImage:[UIImage imageNamed:@"iconfont-tianjiaadd-2.png"]];
        cell.block_label.text = @"添加内容";
        cell.block_label.font = [UIFont systemFontOfSize:11];
//        cell.layer.cornerRadius = 20;
//        cell.backgroundColor = [WebColor gray];
    }
    cell.target = self;
    cell.action = @selector(longPressAction:);
    cell.tag = 1000 + indexPath.item;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    discoverController *dicVC = [[discoverController alloc]init];
#pragma mark 判断创建模块的个数与数据数组中的相比
    if (indexPath.item < [self.dataArray count]) {
        
#pragma mark collectionView 中cell里的点击事件
        //        NSString *str = [self.dataArray[indexPath.item] objectForKey:@"api_url"];
        discoverTitleController *discoverTitle = [[discoverTitleController alloc] init];
        discoverTitle.api_url = [self.dataArray[indexPath.row] objectForKey:@"api_url"];
        discoverTitle.pk = [self.dataArray[indexPath.row] objectForKey:@"pk"];
        
        discoverTitle.type = [self.dataArray[indexPath.row] objectForKey:@"data_type"];
        if ([discoverTitle.pk isEqualToString:@"10516"] || [discoverTitle.pk isEqualToString:@"10721"] || [discoverTitle.pk isEqualToString:@"11365"] || [discoverTitle.pk isEqualToString:@"1"]) {
            WebImageViewController *webImageVC = [[WebImageViewController alloc]init];
            webImageVC.api_url = [self.dataArray[indexPath.row] objectForKey:@"api_url"];
            [self presentViewController:webImageVC animated:YES completion:^{
            }];
            
        }else if ([discoverTitle.type isEqualToString:@"photo"]) {
            ImageViewController *imageVC = [[ImageViewController alloc] init];
            imageVC.api_url = [self.dataArray[indexPath.row] objectForKey:@"api_url"];
            
            [self presentViewController:imageVC animated:YES completion:^{
                
            }];
        }
        else {
            [self presentViewController:discoverTitle animated:YES completion:^{
                
            }];
        }
    } else {
        
        [self.navigationController pushViewController:dicVC animated:YES];
    }
    [dicVC release];
}

- (void)longPressAction:(UICollectionViewCell *)cell
{
#pragma mark 长压添加提示对话框
    if (self.arg == 0) {
        self.arg = 1;
        
        NSString *str = @"你确定要删除么";
        NSString *str1 = [str stringByAppendingFormat:@"[%@]频道么",[self.dataArray[cell.tag - 1000] objectForKey:@"title"]];
        
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"点击删除键删除" contentText:str1 leftButtonTitle:@"取消" rightButtonTitle:@"删除"];
        [alert show];
        
        alert.leftBlock = ^() {
            
            self.arg = 0;
        };
        alert.rightBlock = ^() {
#pragma mark  删除模块  将apiBlockSorts里的详细模块的need_userinfo 改成NO
            self.arg = 0;
            NSString  *str = [NSString string];
            str = [self.dataArray[cell.tag - 1000] objectForKey:@"pk"];
            NSString *str5 = @"apiBlockSorts";
            NSString *str1 = [str5 stringByAppendingFormat:@".plist"];
            NSArray *patharray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *pat11 = [patharray objectAtIndex:0];
            NSString *filepath = [pat11 stringByAppendingPathComponent:str1];
            
            [WeiPlist localSave:@"apiBlockSorts" comaletion:^(id result) {
                self.dataCountArray = [result objectForKey:@"_root" ];
                self.dic = result;
            }];
            
            int a = 0;
            for (NSMutableDictionary *dic in self.dataCountArray) {
                for (NSMutableArray *arr in dic) {
                    arr = [dic objectForKey:@"sons"];
                    for (_kkkk in arr) {
                        if ([[_kkkk objectForKey:@"pk"] isEqualToString:str]) {
                            [_kkkk setObject:@"NO" forKey:@"need_userinfo"];
                            BOOL Result = [self.dic writeToFile:filepath atomically:YES];
                            if (Result) {
                                //                                NSLog(@"写入成功");
                            } else
                            {
                                //                                NSLog(@"写入失败");
                            }
                            a = 1;
                            break;
                        }
                    }
                    if (a == 1) {
                        break;
                    }
                }
            }
#pragma mark 对沙盒里rootBlocks文件进行删除操作
            NSString *strBlock = @"rootBlocks";
            NSString *string = [strBlock stringByAppendingFormat:@".plist"];
            NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *pat1 = [pathArray objectAtIndex:0];
            NSString *filePath = [pat1 stringByAppendingPathComponent:string];
            [WeiPlist localSave:@"rootBlocks" comaletion:^(id result) {
                NSMutableArray *arrBlock = [result objectForKey:@"blocksData"];
                
                for (NSDictionary *dicBlock in arrBlock) {
                    if ([[dicBlock objectForKey:@"pk"] isEqualToString:str]) {
                        //                        NSLog(@"%@",str);
                        [arrBlock removeObject:dicBlock];
                        BOOL write = [result writeToFile:filePath atomically:YES];
                        if (write) {
                            [self updateData];
                            // NSLog(@"写入成功11111");
                        } else
                        {
                            // NSLog(@"写入失败11111");
                        }
                        break;
                    }
                }
                [self.collectionView reloadData];
                
            }];
        };
        
        alert.dismissBlock = ^() {
            
        };
    }
    
}


#pragma mark 颜色转换
-(UIColor *) hexStringToColor: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 charactersif ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appearsif ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}
#pragma mark 天气预报button
- (void)buttonClicked:(UIButton *)button
{
    weatherViewController *weatherVC1 = [[weatherViewController alloc] init];
    
    [self.navigationController pushViewController:weatherVC1 animated:YES];
    
    [weatherVC1 release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
